package com.dev.module_zqc_sleep.mvi.vm

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dev.module_zqc_sleep.mvi.model.Classify
import com.dev.module_zqc_sleep.mvi.model.WhiteNoise
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import java.io.IOException

class AssetsViewModel : ViewModel() {

    private val _assetImages = MutableStateFlow<List<String>>(emptyList())
    val assetImages = _assetImages.asStateFlow()

    private val _assetAudiosSplit = MutableStateFlow<List<List<WhiteNoise>>>(emptyList())
    val assetAudiosSplit = _assetAudiosSplit.asStateFlow()

    private val _classify = MutableStateFlow<List<Classify>>(emptyList())
    val classify = _classify.asStateFlow()

    fun loadAssetImages(context: Context, folderIndex: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            val images = mutableListOf<String>()
            try {
                val path = "wallpaper_$folderIndex"
                context.assets.list(path)?.forEach { file ->
                    if (file.endsWith(".png")) {
                        images.add("$path/$file")
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            _assetImages.value = images
        }
    }

    fun loadWhiteNoiseAndClassifyJson(context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val whiteNoiseDeferred = async {
                    context.assets.open("white_noise.json").bufferedReader().use { reader ->
                        val jsonString = reader.readText()
                        Json.decodeFromString<List<WhiteNoise>>(jsonString)
                    }
                }
                val classifyDeferred = async {
                    context.assets.open("classify.json").bufferedReader().use { reader ->
                        val jsonString = reader.readText()
                        Json.decodeFromString<List<Classify>>(jsonString)
                    }
                }
                _assetAudiosSplit.value = splitWhiteNoises(whiteNoiseDeferred.await())
                _classify.value = classifyDeferred.await()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    private fun splitWhiteNoises(whiteNoises: List<WhiteNoise>): List<List<WhiteNoise>> {
        val distributed = mutableListOf<List<WhiteNoise>>()
        val totalTabs = 7
        for (i in 0 until totalTabs) {
            distributed.add(mutableListOf())
        }

        whiteNoises.forEachIndexed { index, whiteNoise ->
            val tabIndex = index % totalTabs
            (distributed[tabIndex] as MutableList).add(whiteNoise)
        }

        return distributed
    }
}
